package com.yzp.zk_lock;

import org.I0Itec.zkclient.ZkClient;

import java.util.concurrent.CountDownLatch;


/**
 * @title: ZookeeperAbstractLock
 * @Author: yzp
 * @Date: 2019/7/7 9:50
 * @Version 1.0
 */
//将重复的代码抽象到子类中（设计模式模板方法设计模式）
public abstract class ZookeeperAbstractLock implements ExtLock {
    //zk连接地址
    private static final String CONNECT_STRING = "192.168.241.133:2181";
    //创建zk连接
    protected ZkClient zkClient = new ZkClient(CONNECT_STRING);
    protected String lockPath = "/lockPath";
    protected CountDownLatch countDownLatch = null;

    @Override
    public void getLock() {
        if (tryLock()) {
            //获取到锁
        } else {
            waitLock();
            getLock();
        }
    }

    //获取锁资源
    abstract boolean tryLock();

    //等待
    abstract void waitLock();

    @Override
    public void unLock() {
        if (zkClient != null) {
            zkClient.close();
        }
    }
}
